/*
 * Copyright (c) 2011
 * UNPUBLISHED PROPRIETARY SOURCE CODE.
 */

package com.webservice.service.impl;

import com.webservice.domain.UserPhoto;
import com.webservice.domain.dao.UserPhotoDao;
import com.webservice.exception.UserPhotoNotFoundException;
import com.webservice.service.IUserPhotoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.inject.Inject;

/**
 * {@link UserPhoto} management service.
 *
 * @author vkolodrevskiy
 */
@Service
public class UserPhotoService implements IUserPhotoService {
    private static final Logger logger = LoggerFactory.getLogger(UserPhotoService.class);

    private final UserPhotoDao userPhotoDao;

    @Inject
    public UserPhotoService(UserPhotoDao userPhotoDao) {
        this.userPhotoDao = userPhotoDao;
    }

    @Override
    public UserPhoto createOrUpdateUserPhoto(UserPhoto userPhoto) {
        UserPhoto photo = userPhotoDao.findByUserId(userPhoto.getUserId());
        if(photo == null) {
            userPhotoDao.insert(userPhoto);
            logger.info("Created user photo for user with id = " + userPhoto.getUserId());
        }
        else {
            userPhotoDao.update(userPhoto);
            logger.info("Updated user photo with id = " + userPhoto.getId());
        }

        return userPhotoDao.findById(userPhoto.getId());
    }

    @Override
    public UserPhoto findPhotoByUserId(long userId) throws UserPhotoNotFoundException {
        UserPhoto userPhoto = userPhotoDao.findByUserId(userId);
        if(userPhoto == null) {
            throw new UserPhotoNotFoundException("User photo for user with id = [" + userId + "] was not found.");
        }

        logger.info("Found user photo for user with id = [" + userId + "]");
        return userPhoto;
    }
}
